package com.it.ymcc.utils;

import com.it.ymcc.exception.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class UserUtils {

    /**
     * 获取当前登录用户信息
     * @return Payload对象，包含用户信息和权限信息
     */
    public static Payload getCurrentUser() {
        // 获取当前请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new BusinessException("无法获取当前请求");
        }

        HttpServletRequest request = requestAttributes.getRequest();
        
        // 从请求中获取payload
        Payload payload = (Payload) request.getAttribute("payload");
        if (payload == null) {
            throw new BusinessException("用户未登录");
        }
        
        return payload;
    }

    /**
     * 检查当前用户是否具有指定权限
     * @param permission 权限标识
     * @return 如果有权限返回true，否则返回false
     */
    public static boolean hasPermission(String permission) {
        Payload payload = getCurrentUser();
        return payload.getPermissions() != null && payload.getPermissions().contains(permission);
    }

    /**
     * 检查当前用户是否具有任意一个指定权限
     * @param permissions 权限标识数组
     * @return 如果有任意一个权限返回true，否则返回false
     */
    public static boolean hasAnyPermission(String... permissions) {
        Payload payload = getCurrentUser();
        if (payload.getPermissions() == null) {
            return false;
        }
        
        for (String permission : permissions) {
            if (payload.getPermissions().contains(permission)) {
                return true;
            }
        }
        
        return false;
    }
}